
package com.woniuxy.yogaapp.handler;

import java.io.File;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.woniuxy.yogaapp.service.CoachService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.woniuxy.yogaapp.pojo.ClubCoach;
import com.woniuxy.yogaapp.pojo.Coach;
import com.woniuxy.yogaapp.pojo.Student;
import com.woniuxy.yogaapp.pojo.YogaClub;
import com.woniuxy.yogaapp.util.RegexUtil;
import com.woniuxy.yogaapp.dto.Check;
import lombok.Data;

@Data
@Controller
@RequestMapping("/coach")
@Scope("prototype")
public class CoachHandler {

	@Resource
	private CoachService coachService;

	/**
	 * 教练申请加入某场馆 需要 前端传来 场馆yid uid yname
	 * 
	 * @return
	 */
	@RequestMapping("/applyForClub")
	@ResponseBody
	public String applyForClub(YogaClub club) {
		Coach coach = new Coach();
		// 1.获取subject对象
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		int uid = (int) session.getAttribute("uid");
		coach.setUid(uid);
		Coach coachMe = coachService.findCoachByUid(coach);
		int cid = coachMe.getCid(); // 该教练的cid
		int cuid = coachMe.getUid();// 该教练的 用户id
		String cname = coachMe.getCname();// 该教练的 名字
		ClubCoach clubCoach = new ClubCoach(club.getYid(), cid, club.getUid(), cuid, club.getYname(), cname, 0);
		String result = coachService.applyForClub(clubCoach);
		return result;
	}

	// 查询所有
	@RequestMapping("/all")
	@ResponseBody
	public List<Coach> coachAll() {
		return coachService.findAllCoach();
	}

	// 根据教练id查学生
	@RequestMapping("/bycid")
	@ResponseBody
	public List<Student> findByCidStudent() {
		Coach c = coachService.findByCid(1);
		System.out.println(c.getStudents());
		return c.getStudents();
	}

	// 根据教练uid查询该个教练

	@RequestMapping("/one")
	@ResponseBody
	public Coach findOneCoach(int uid) {
		return coachService.findOneCoach(uid);
	}

	/*
	 * 点击个人信息完善 查看数据库查看该用户的个人信息 显示到前端
	 */
	@RequiresRoles(value = { "coach", "common" }, logical = Logical.OR)
	@RequestMapping("/showMe")
	public ModelAndView showMe() {
		Coach coach = new Coach();
		// 1.获取subject对象
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		int uid = (int) session.getAttribute("uid");
		coach.setUid(uid);
		Coach coachMe = coachService.findCoachByUid(coach);
		if (coachMe == null) {
			coachMe = new Coach();
		}
		// 3.跳转页面
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("coach", coachMe);
		modelAndView.setViewName("/coachInfo.html");
		return modelAndView;
	}

	// 教练基本信息添加
	/*
	 * 1.教练名字cname 电话ctel qq：cqq 年龄：cage 性别csex 头像：cimage 信息权限 power 昵称 cnikname
	 * 用户编号uid 邮箱 cmail 是否接课 state 流派cgenre 空闲时间freetime
	 * 
	 */
	@RequestMapping("/info")
	public String addCoachInfo(Coach coach, @RequestParam("headImage") MultipartFile file, HttpServletRequest request)
			throws Exception {
		String result = "添加失败！";
		// 1.获取subject对象
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		int uid = (int) session.getAttribute("uid");
		coach.setUid(uid);
		// 1.电话合法性判断
		if (coach.getCtel() != null && coach.getCtel().length() != 0) {
			if (!RegexUtil.isMobile(coach.getCtel())) {
				request.setAttribute("coachtishi", "电话号码有误，请输入正确11位手机号码！");
				return "/html/coachtishi.html";
			}
		}
		// 2.邮箱合法性判断
		if (coach.getCmail() != null && coach.getCmail().length() != 0) {
			if (!RegexUtil.isEmail(coach.getCmail())) {
				request.setAttribute("coachtishi", "邮箱格式有误！");
				return "/html/coachtishi.html";
			}
		}
		// 判断头像是否为空 上传的头像也为空 添加默认头像
		if (file.getSize() == 0 && (coach.getCimage() == null || coach.getCimage().length() == 0)) {
			// 2.1.获取文件的路径（相对路径），将所有的注册信息保存到数据库
			// 添加默认老鼠头像
			coach.setCimage("../image/1.jpg");
		}
		// 如果上传的头像不为空 将图片的路径给student.simage 赋值
		if (file.getSize() != 0) {
			// 执行到此处，前端提交的数据全拿到了
			// 1.将文件保存到Tomcat服务器本地
			// 1.1.获取保存文件的文件夹的路径
			String path = request.getServletContext().getRealPath("");
			File dir = new File(path);
			// 获得webapp文件夹的file对象
			File webapp = dir.getParentFile();
			String fileName = file.getOriginalFilename();
			// 生成新文件名
			String newName = UUID.randomUUID().toString();
			// 得到文件后缀名
			String type = fileName.substring(fileName.lastIndexOf("."));
			newName += type;
			// 拼接新文件的路径
			File uploadFile = new File(webapp, "webapp\\image\\" + newName);
			// 1.2.将文件保存到服务器本地
			file.transferTo(uploadFile);
			// 2.1.获取文件的路径（相对路径），将所有的注册信息保存到数据库
			coach.setCimage("/image/" + newName);
		}
		// 数据库查询该用户 看coach表有没有 如果有调用update方法 如果是新用户就调用插入方法
		Coach coach1 = coachService.findCoachByUid(coach);
		if (coach1 != null) {
			// 调用update方法
			int row = coachService.updateCoachInfo(coach);
			if (row == 1) {
				request.setAttribute("coachtishi", "修改成功！");
				return "/html/coachtishi.html";
			}
		} else {
			// 新用户调用插入方法 保存coach到数据库
			result = coachService.addCoachInfo(coach);
			request.setAttribute("coachtishi", result);
			return "/html/coachtishi.html";
		}
		request.setAttribute("coachtishi", result);
		return "/html/coachtishi.html";
	}

	/**
	 * 教练添加资格认证信息 待管理员认证 1.需要前端参数 身份证cidcard 地址caddress describe（自我介绍 varchar32）
	 */
	@RequestMapping("/approve")
	public String approvePower(Coach coach, HttpServletRequest request) {
		String result = "认证请求发送失败！";
		// 1.获取该用的的uid
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		int uid = (int) session.getAttribute("uid");
		coach.setUid(uid);
		Coach co = coachService.findCoachByUid(coach);
		if (co == null) {
			request.setAttribute("coachtishi", "你未完成基本信息填写，不能进行此操作！");
			return "/html/coachtishi.html";

		}
		if (coach.getCidcard() == null || coach.getCidcard().length() == 0) {
			request.setAttribute("coachtishi", "身份证号码不能为空！");
			return "/html/coachtishi.html";

		}
		if (coach.getCaddress() == null || coach.getCaddress().length() == 0) {
			request.setAttribute("coachtishi", "地址不能为空!");
			return "/html/coachtishi.html";
		}
		if (!RegexUtil.isIDCard(coach.getCidcard())) {
			request.setAttribute("coachtishi", "身份证号码不正确，请输入正确18位身份证号码！");
			return "/html/coachtishi.html";
		}
		coach.setApprove(0);
		// 2.添加认证信息待认证
		result = coachService.approvePower(coach);
		request.setAttribute("coachtishi", result);
		return "/html/coachtishi.html";
	}

	// 教练点击确认，更新状态,传入deid及状态 如果通过flag来判断是接受还是拒绝
	/*
	 * 前端参数：cid,sid,oid,flag
	 *
	 */
	/* boolean flag = false; */
	/*
	 * check.setCid(1); check.setSid(1); check.setOid(7);
	 */
	@RequestMapping("/check")
	@ResponseBody
	public String checkOrder(Check check) {

		int i = -1;

		// 如果拒绝
		if (check.isFlag()) {
			check.setState(2);
			i = coachService.updateOrder(check);
			if (i > 0) {
				return "已拒绝";
			}
		} else {
			check.setState(3);
			String result = coachService.updateOrderCheck(check);

			return result;

		}

		return "确认失败";
	}

	// 教练上完课后点击上完了课了，通知学员（未通知）
	/*
	 * 教练上课完成后点击确认上课完成 -1。更改订单状态并向学员发起通知传入参数did 2.，state 更新数据库 前端传入sid，cid,oid
	 */
	/*
	 * check.setOid(7); check.setCid(1); check.setSid(1);
	 */
	@RequestMapping("/checkco")
	@ResponseBody
	public String checkOrderCo(Check check) {
		check.setState(4);

		String result = coachService.postOrder(check);

		return result;
	}

	// 再次发送我已经完成订单，创建新的小订单
	/*
	 * 通过前端传入oid,在小订单表中先新创建一个订单表，并赋值oid给改 传入sid，cid ,oid
	 */
	/* check.setOid(2); */
	@RequestMapping("/recheckco")
	@ResponseBody
	public String recheckOrderCo(Check check) {

		check.setState(4);

		String result = coachService.repostOrder(check);
		return result;
	}

	// 展示所属会馆名字
	@RequestMapping("/showclubname")
	@ResponseBody
	public List<String> showClubName(int uid) {
		List<String> result = coachService.showClubName(uid);
		return result;
	}
}
